package com.beidouapp.aspect;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Before;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.beidouapp.domain.annotation.Right;
import com.beidouapp.security.model.ReturnDataInfo;
import com.beidouapp.security.utils.DscpCommUtils;
import com.beidouapp.security.utils.SysContent;

import net.sf.json.JSONException;
import net.sf.json.JSONObject;

//@Aspect
//@Component
public class DataAccessAspect
{
	private final Logger logger = LoggerFactory
			.getLogger(DataAccessAspect.class);

	/**
	 * 环绕通知 用于拦截数据访问权限
	 * 
	 * @param jp
	 *            切点
	 * @param right
	 * @throws Exception
	 */
	// 标注该方法体为后置通知，当目标方法执行成功后执行该方法体
	@Before("within(com.beidouapp..mvc.*) && @annotation(right)")
	public void checkPermission(Right right) throws Exception
	{
		try
		{
			String[] rightCode = right.name();
			HttpServletRequest request = SysContent.getRequest();
			boolean check = false;
			if (rightCode != null && rightCode.length > 0)
			{
				List<String> belongRights = DscpCommUtils.getResource(request.getSession());
				for (int i = 0; i < rightCode.length; i++)
				{
					for (String belongRight : belongRights)
					{
						if (rightCode[i].equals(belongRight))
						{
							check = true;
							break;
						}
					}
				}
			}
			if(!check)
			{
				flush2Response(request, SysContent.getResponse());
			}
		}
		catch (Throwable e)
		{
			e.printStackTrace();
		}
	}

	// 标注该方法体为异常通知，当目标方法出现异常时，执行该方法体
	@AfterThrowing(pointcut = "within(com.beidouapp..mvc.*) && @annotation(right)", throwing = "ex")
	public void addAfterThrowing(final JoinPoint jp, Right right, Exception ex)
	{
		final Logger logger = getLog(jp);
		if (ex != null)
		{
			logger.error(ex.getLocalizedMessage(), ex);
		}
	}
	
	protected void flush2Response(HttpServletRequest request, HttpServletResponse response) throws IOException, JSONException
	{
		logger.info("session失效!");
		String url = request.getRequestURI();
		if(url.contains("/api/special/page/add"))
		{
//			throw new TokenException(TokenException.AUTH_ERROR_CODE, "权限不足");
		}
		else if (request.getContentType() != null && request.getContentType().indexOf("json") != -1)
		{
			ReturnDataInfo<String> info = new ReturnDataInfo<String>();
			info.setMessage("数据访问失败!");
			info.setStatusCode(503);
			JSONObject root = JSONObject.fromObject(info);
			response.setContentType("text/html; charset=utf-8");
			PrintWriter writer = response.getWriter();
			writer.print(root);
			writer.flush();
		}
		else
		{
			request.setAttribute("message", "您没有权限访问当前页面!");
			try {
				request.getRequestDispatcher("/api/toError").forward(request, response);
			} catch (ServletException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			//response.sendRedirect(request.getContextPath() + "/api/toError");
		}
	}
	
	
	private Logger getLog(final JoinPoint joinPoint)
	{
		final Object target = joinPoint.getTarget();

		if (target != null)
		{
			return LoggerFactory.getLogger(target.getClass());
		}

		return LoggerFactory.getLogger(getClass());
	}
}
